﻿/* Copyright 2010 Igor Francé
 * 
 * This file is part of ECMADoc (http://ecmadoc.codeplex.com).
 * 
 * ECMADoc is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * ECMADoc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with ECMADoc. 
 * If not, see http://www.gnu.org/licenses/.
 */
namespace EcmaDoc.Core
{
	using System;
	using System.IO;
	using System.Reflection;

	/// <summary>
	/// Provides various global utility methods and properties.
	/// </summary>
	public static class Utilities
	{
		/// <summary>
		/// Gets the directory from which the assembly is being run.
		/// </summary>
		public static string ApplicationPath
		{
			get
			{
				return Path.GetDirectoryName(
					Assembly.GetExecutingAssembly()
						.CodeBase
						.Replace("file:///", string.Empty)
						.Replace("/", "\\"));
			}
		}

		/// <summary>
		/// Expands the specified relative path to the full physical version of it 
		/// (resolved from the location of the currently executing assembly).
		/// </summary>
		/// <param name="relativePath">The relative path to resolve.</param>
		/// <returns>The expanded version of the specified relative path</returns>
		/// <exception cref="ArgumentNullException">If <paramref name="relativePath"/> is <c>null</c> or empty.</exception>
		public static string ExpandPath(string relativePath)
		{
			if (string.IsNullOrEmpty(relativePath))
				throw new ArgumentNullException("relativePath");

			if (Path.IsPathRooted(relativePath))
				return relativePath;

			string expanded = Path.Combine(ApplicationPath, relativePath);

			if (File.Exists(expanded))
				return new FileInfo(expanded).FullName;

			if (Directory.Exists(expanded))
				return new DirectoryInfo(expanded).FullName;

			return expanded;
		}
	}
}
